//
//  BaseTabbarController.swift
//  BaseTabbarController
//
//  Created by mini on 2025/4/28.
//

import Foundation
import UIKit

class BaseTabbarController: UITabBarController, UITabBarControllerDelegate {

    lazy var loginView: LoginView = {
        let result = LoginView()
        return result
    }()
    
    var lastSelectedIndex: Int = 0
    let bgImages = [
        UIImage(named: "icon_tabbar_bg_1"),
        UIImage(named: "icon_tabbar_bg_2"),
        UIImage(named: "icon_tabbar_bg_3"),
        UIImage(named: "icon_tabbar_bg_4"),
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        setValue(CustomTabBar(), forKey: "tabBar")
        setupViewControllers()

        delegate = self
        // 设置初始背景图
        if let customTabBar = tabBar as? CustomTabBar {
            customTabBar.setBackgroundImage(bgImages[0])
        }
    }

    private func setupViewControllers() {
        // 添加你的视图控制器
        let homePageVC = createViewController(HomePageVC(), title: "", imageName: "icon_tabbar_transparent", selectImageName: "icon_tabbar_home")
        let orderVC = createViewController(OrderVC(), title: "", imageName: "icon_tabbar_transparent", selectImageName: "icon_tabbar_order")
        let mineVC = createViewController(MineVC(), title: "", imageName: "icon_tabbar_transparent", selectImageName: "icon_tabbar_mine")
        let settingVC = createViewController(SettingVC(), title: "", imageName: "icon_tabbar_transparent", selectImageName: "icon_tabbar_setting")
        viewControllers = [homePageVC, orderVC, mineVC, settingVC]
    }

    private func createViewController(_ viewController: UIViewController, title: String, imageName: String?, selectImageName: String?) -> UIViewController {
        // 创建普通状态的图片，设置为原始渲染模式
        let normalImage = isStr(imageName) ? UIImage(named: imageName ?? "")?.withRenderingMode(.alwaysOriginal) : nil
        // 创建选中状态的图片，设置为原始渲染模式
        let selectedImage = isStr(selectImageName) ? UIImage(named: selectImageName ?? "")?.withRenderingMode(.alwaysOriginal) : nil
        viewController.tabBarItem = UITabBarItem(title: title, image: normalImage, selectedImage: selectedImage)
        return viewController
    }

    // MARK: - 点击切换 tabbar
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        feedback()
        guard let idx = tabBar.items?.firstIndex(of: item) else { return }
        // 获取所有的 tabBar 按钮
        let buttons = tabBar.subviews.compactMap { subview -> UIView? in
            if subview.description.contains("UITabBarButton") {
                return subview
            }
            return nil
        }
        // 确保索引有效并执行动画
        if buttons.count > idx {
            bounceAnimation(for: buttons[idx])
        }
    }

    // 监听 tab 切换，切换背景图
    func tabBarController(_: UITabBarController, didSelect viewController: UIViewController) {
        if let index = viewControllers?.firstIndex(of: viewController),
           let customTabBar = tabBar as? CustomTabBar
        {
            customTabBar.setBackgroundImage(bgImages[index])
        }
    }

    // 未登录 - 弹窗
    func tabBarController(_: UITabBarController, shouldSelect _: UIViewController) -> Bool {
        if !isStr(GlobalData.sharedInstance.GB_SessionID) {
            feedback()
            loginView.show()
            return false
        }
        return true
    }

    // MARK: - 动画
    private func bounceAnimation(for view: UIView) {
        let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
        scaleAnimation.values = [1.0, 0.8, 1.2, 0.9, 1.0]
        scaleAnimation.duration = 0.4
        scaleAnimation.calculationMode = .cubic
        view.layer.add(scaleAnimation, forKey: nil)
    }
}
